import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { Component } from '@angular/core';
import * as echarts from 'echarts';
import { WorkbenchService } from 'src/app/@core/mock/datasERVICE/workbench.service';

@Component({
  selector: 'app-inventory-workbench',
  templateUrl: './inventory-workbench.component.html',
  styleUrls: ['./inventory-workbench.component.scss']
})
export class InventoryWorkbenchComponent {
  amountData: any = {
    "todayInWarehouseAmount": 0,
    "todayInWarehouseDayRate": 0,
    "monthInWarehouseAmount": 0,
    "monthInWarehouseMonthRate": 0,
    "todayOutWarehouseAmount": 0,
    "todayOutWarehouseDayRate": 0,
    "monthOutWarehouseAmount": 0,
    "monthOutWarehouseMonthRate": 0,
    "totalrealTimeInventory": 0,
    "totalInWarehouseAmount": 0,
    "totalOutWarehouseAmount": 0
  }
  todoList: any = {
    "allWarehouseTasksCount": 0,
    "otherInWarehouseTasksCount": 0,
    "saleOutWarehouseTasksrCount": 0,
    "saleReturnTasksrCount": 0,
    "purchaseInWarehouseTasksCount": 0,
    "purchaseReturnTasksCount": 0,
    "productOutWarehouseTasksCount": 0,
    "productInWarehouseTasksCount": 0,
    "productReturnTasksCount": 0
  }
  statistics = []
  constructor(private StorehouseService:StorehouseService) { }
  ngOnInit(): void {
    this.StorehouseService.GetWarehouseAmountData().subscribe((data: any) => {
      this.amountData = data;
    })
    this.StorehouseService.GetWarehouseToDoList().subscribe((data: any) => {
      this.todoList = data;
    })
    this.StorehouseService.GetWarehouseInventoryInOrOutStatistics().subscribe((data: any) => {
      const months = data.map((item: any) => item.month);
      const inboundData = data.map((item: any) => item.inboundAmount);
      const outboundData = data.map((item: any) => item.outboundAmount);
      this.saleData(months, inboundData, outboundData);
    });
    this.StorehouseService.GetWarehouseInventoryOutStatistics().subscribe((data: any) => {
      const filteredData = this.getLastThreeMonthsData(data);
      const months = filteredData.map((item: any) => item.month);
      const totalOutboundData = filteredData.map((item: any) => item.totalOutboundAmount);
      const saleReturnData = filteredData.map((item: any) => item.saleReturnAmount);
      const productionOutboundData = filteredData.map((item: any) => item.productionOutboundAmount);
      const purchaseReturnData = filteredData.map((item: any) => item.purchaseReturnAmount);
      this.deliveryData(months, totalOutboundData, saleReturnData, productionOutboundData, purchaseReturnData);
    });
    this.StorehouseService.GetWarehouseInventoryInStatistics().subscribe((data: any) => {
      const filteredData = this.getLastThreeMonthsData(data);
      const months = filteredData.map((item: any) => item.month);
      const totalInboundData = filteredData.map((item: any) => item.totalInboundAmount);
      const otherInboundData = filteredData.map((item: any) => item.otherInboundAmount);
      const salesReturnData = filteredData.map((item: any) => item.saleReturnAmount);
      const purchaseInboundData = filteredData.map((item: any) => item.purchaseDeliveryAmount);
      const productionInboundData = filteredData.map((item: any) => item.productionInboundAmount);
      const productionReturnData = filteredData.map((item: any) => item.productionReturnAmount);
      this.renderInboundChart(months, totalInboundData, otherInboundData, salesReturnData, purchaseInboundData, productionInboundData, productionReturnData);
    });
  }
  saleData(months: string[], inboundData: number[], outboundData: number[]){
    const option = {
      tooltip: {
        show: true,
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '5%',
        top: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months
      },
      yAxis: {
        type: 'value',
        name: '数量',
        axisLine: {
          show: true,
        },
        axisLabel: {
          formatter: '{value} '
        },
      },
      series: [
        {
          data: outboundData,
          name: "出库量",
          barWidth: '30%',
          type: 'bar',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ]),
            barBorderRadius: [5, 5, 0, 0] // 添加弧度
          },
          label: {
            show: true,
            position: 'top',
            formatter: function (params: any) {
              return `${params.value}`;
            }
          },
        },
        {
          data: inboundData,
          name: "入库量",
          barWidth: '30%',
          type: 'bar',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#f6efa6' },
              { offset: 0.5, color: '#f3c623' },
              { offset: 1, color: '#f3c623' }
            ]),
            barBorderRadius: [5, 5, 0, 0] // 添加弧度
          },
          label: {
            show: true,
            position: 'top',
            formatter: function (params: any) {
              return `${params.value} `;
            }
          },
        }
      ]
    };
    const myChart = echarts.init(document.getElementById('xiaoshoue') as HTMLElement);
    myChart.setOption(option);
    myChart.resize(); // 初始化后立即调用 resize 方法
    window.addEventListener('resize', function () {
      myChart.resize();
    });
  }

getLastThreeMonthsData(data: any[]): any[] {
  const currentDate = new Date();
  const currentMonth = currentDate.getMonth() + 1; // JavaScript 的月份是从 0 开始的，所以需要加 1
  const currentYear = currentDate.getFullYear();

  // 计算前两个月的月份和年份
  const previousMonth1 = new Date(currentYear, currentMonth - 2);
  const previousMonth2 = new Date(currentYear, currentMonth - 3);

  // 格式化月份和年份
  const formatMonth = (date: Date) => `${date.getFullYear()}年${date.getMonth() + 1}月`;

  const currentMonthStr = formatMonth(currentDate);
  const previousMonth1Str = formatMonth(previousMonth1);
  const previousMonth2Str = formatMonth(previousMonth2);

  // 过滤数据，只保留本月和前两个月的数据
  return data.filter((item: any) =>
    item.month === currentMonthStr || item.month === previousMonth1Str || item.month === previousMonth2Str
  );
}
  deliveryData(months: string[], totalOutboundData: number[], saleReturnData: number[], productionOutboundData: number[], purchaseReturnData: number[]): void {
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['出库总量', '销售发货数', '生产领料数', '采购退货数'],
        right: '0%', // 或者使用 'right' 关键字
        left: "16%",
      },
      grid: {
        left: '0%',
        right: '0%',
        top: "30%",
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months,
        name: "日期"
      },
      yAxis: {
        type: 'value',
        name: "数量"
      },
      series: [
        {
          name: '出库总量',
          type: 'bar',
          barWidth: '50%',
          stack: '总量',
          data: totalOutboundData
        },
        {
          name: '销售发货数',
          type: 'bar',
          barWidth: '50%',
          stack: '总量',
          data: saleReturnData
        },
        {
          name: '生产领料数',
          type: 'bar',
          barWidth: '50%',
          stack: '总量',
          data: productionOutboundData
        },
        {
          name: '采购退货数',
          type: 'bar',
          barWidth: '50%',
          stack: '总量',
          data: purchaseReturnData
        }
      ]
    }
    const myChart = echarts.init(document.getElementById('jiaofu') as HTMLElement)
    myChart.setOption(option)
    myChart.resize() // 初始化后立即调用 resize 方法
    window.addEventListener('resize', function () {
      myChart.resize()
    });
  }
  getLastThreeDays(): string[] {
    const dates = []
    for (let i = 2; i >= 0; i--) {
      const date = new Date()
      date.setDate(date.getDate() - i)
      const formattedDate = `${date.getMonth() + 1}月${date.getDate()}日`
      dates.push(formattedDate)
    }
    return dates;
  }
  renderInboundChart(months: string[], totalInboundData: number[], otherInboundData: number[], salesReturnData: number[], purchaseInboundData: number[], productionInboundData: number[], productionReturnData: number[]): void {
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['入库总量', '其他入库数', '销售退货数', '采购到货数', '生产入库', '生产退料数'],
        right: '0%', // 或者使用 'right' 关键字
        left: "16%",
      },
      grid: {
        left: '0%',
        right: '0%',
        top: "34%",
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months
      },
      yAxis: {
        type: 'value',
        name: '数量'
      },
      series: [
        {
          name: '入库总量',
          type: 'bar',
          barWidth: '50%',
          stack: '总量',
          data: totalInboundData,
          itemStyle: {
            color: '#1f77b4' // 蓝色系
          }
        },
        {
          name: '其他入库数',
          type: 'bar',
          barWidth: '50%',
          stack: '总量',
          data: otherInboundData,
          itemStyle: {
            color: '#ff7f0e' // 红色系
          }
        },
        {
          name: '销售退货数',
          type: 'bar',
          barWidth: '50%',
          stack: '总量',
          data: salesReturnData,
          itemStyle: {
            color: '#d62728' // 绿色系
          }
        },
        {
          name: '采购到货数',
          type: 'bar',
          barWidth: '50%',
          stack: '总量',
          data: purchaseInboundData,
          itemStyle: {
            color: '#2ca02c' // 浅蓝色系2ca02c
          }
        },
        {
          name: '生产入库',
          type: 'bar',
          barWidth: '50%',
          stack: '总量',
          data: productionInboundData,
          itemStyle: {
            color: '#17becf' // 黄色系 17becf
          }
        },
        {
          name: '生产退料数',
          type: 'bar',
          barWidth: '50%',
          stack: '总量',
          data: productionReturnData,
          itemStyle: {
            color: '#bcbd22' // 红色系
          }
        }
      ]
    }
    const myChart = echarts.init(document.getElementById('inboundChart') as HTMLElement)
    myChart.setOption(option)
    myChart.resize() // 初始化后立即调用 resize 方法
    window.addEventListener('resize', function () {
      myChart.resize();
    })
  }
}
